package com.junqson.je.content.service;

import com.junqson.je.common.UserHolder;
import com.junqson.je.common.exception.BizException;
import com.junqson.je.common.model.vo.SimpleUserInfo;
import com.junqson.je.common.util.AppUtil;
import com.junqson.je.content.model.CommentModel;
import com.junqson.je.content.model.dto.CommentDTO;
import com.junqson.je.content.model.vo.CommentVo;
import com.junqson.je.content.repo.CommentRepo;
import com.junqson.je.content.repo.PostRepo;
import com.junqson.je.content.util.PageUtil;
import com.junqson.je.content.util.UserInfoCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Descriptions
 * @Company
 * @Author Junqson
 * @Date 2020/2/11 9:05
 * @Version 1.0
 */
@Service
@Slf4j
public class CommentService {

    @Autowired
    CommentRepo commentRepo;

    @Autowired
    PostRepo postRepo;

    @Autowired
    UserInfoCache userInfoCache;

    @Transactional
    public void addComment(CommentDTO dto) {
        postRepo.findById(dto.getPostId()).orElseThrow(() -> new BizException("帖子不存在"));
        CommentModel model = new CommentModel();
        model.setPostId(dto.getPostId());
        model.setUserId(UserHolder.get().getUserId());
        model.setContent(dto.getContent());
        commentRepo.save(model);
        postRepo.changeUpdateTime(model.getCommentTime(), model.getPostId());
    }


    public void deleteByCommentId(Long commentId) {
        commentRepo.deleteById(commentId);
    }

    public void deleteByPostId(Long postId) {
        commentRepo.deleteAllByPostId(postId);
    }


    public Long countCommentByPostId(Long postId) {
        return commentRepo.countAllByPostId(postId);
    }

    public CommentModel getById(Long commentId) {
        return commentRepo.findById(commentId).orElseThrow(() -> new BizException("评论不存在"));
    }

    public List<CommentVo> pageByPostId(Long postId, Integer page, Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "commentTime");
        Pageable pageable = PageUtil.getPageable(page, size, sort);
        Page<CommentModel> models = commentRepo.findByPostId(postId, pageable);
        return models.getContent().stream().map(this::convertToCommentVo).collect(Collectors.toList());
    }

    public CommentVo convertToCommentVo(CommentModel model) {
        CommentVo vo = new CommentVo();
        AppUtil.copyPropertiesIgnoreNull(model, vo);
        SimpleUserInfo userInfo = userInfoCache.getUserInfo(model.getUserId());
        vo.setUserInfo(userInfo);
        return vo;
    }

}
